import sys
from dotenv import dotenv_values
env_vars = dotenv_values(".env")
sys.path.append(env_vars["DEFAULT_PATH"])
from app.config.db import DbConfig,db_config
from sqlalchemy.orm import close_all_sessions
import asyncio
from aiomysql.sa  import  create_engine
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.model.user import User
class AsyncDbUtils:
    """
    AsyncDbUtils 异步DB工具类
    :version: 1.4
    :date: 2020-02-11
    """

    sess: AsyncSession = None
    default_config: DbConfig = db_config

    def __init__(self, config: DbConfig = None):
        if not config:
            config = self.default_config

        self.sess = self._create_async_scoped_session(config)
    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc, traceback):
        pass
        # await self.sess.close()
        await self.engine.dispose()
        
    @classmethod
    def _create_async_scoped_session(self, config: DbConfig):
        engine = create_async_engine(
            config.get_url(),
            pool_size=config.pool_size,
            max_overflow=config.max_overflow,
            pool_recycle=config.pool_recycle,
            echo=config.echo,
        )
        self.engine=engine
        print('====已建立连接====')
        async_sessionmaker = sessionmaker(engine, expire_on_commit=False,class_=AsyncSession)
        return  async_sessionmaker

# db_instance=

async def asyncmain():
    db=AsyncDbUtils(db_config)
    async with db.sess() as session:
       data=User(name='测试',avatar='123',openid='111')
       session.add(data)
       await session.commit()
    await db.engine.dispose()
   
        
    # sess
async def main2():
    await asyncio.gather(*[asyncmain() for item in range()])
if __name__ == '__main__':
    import time
    a=time.time()
    asyncio.run(main2())
    #  
    print(time.time()-a,'-----------------')
    
    
    async def main():
      
        engine = await create_engine(
        user=db_config.username,
        db=db_config.database,
        password=db_config.password,
        host=db_config.host,
        port=db_config.port,
        )
        async with engine.acquire() as conn:
            async with conn.begin() as transaction:
                await conn.add
                await transaction.commit()
                # async for row in res:
                #     print(row.id, row.val)

        engine.close()

        await engine.wait_closed()